const baseUrl = `${window.location.origin}/`;
layui.use(['jquery','upload','element','table','layer','form','laydate','util'], function(){
    var table = layui.table,

        layer = layui.layer;
    var upload = layui.upload;
    var laydate = layui.laydate;
    var form=layui.form;
    var util = layui.util;
    $ = layui.jquery;
    var url = window.location.href.toString();
    var param = $.parseParams(url.split('?')[1] || '');
    var recordInspectId = param.recordInspectId ? param.recordInspectId : null;
    var status = param.status ? param.status : null;

    function getLimit(date) {
        return {
            year: date.year,
            month: date.month - 1,//关键
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds: 0
        };
    }
    //活动结束时间
    var endDate= laydate.render({
        elem: '#endDate',//选择器结束时间
        type: 'datetime',
        trigger:'click',//解决一闪而过的问题
        done: function(value,date){
            startDate.config.max = getLimit(date);
        }
    });
    //活动开始时间
    var startDate=laydate.render({
        elem: '#startDate',
        type: 'datetime',
        max: "2099-12-31",//设置一个默认最大值
        trigger:'click',
        done: function(value, date){
            endDate.config.min =  getLimit(date);
        }
    });
    loadLineList();

    table.render({
        elem: '#insPointRecordsTable'
        ,url: baseUrl+'/insPointRecord/listByCondition'
        ,method: 'post'
        ,title: '巡检点位记录表'
        ,where:{recordInspectId: recordInspectId,status:status}
        ,cols: [[
            {type:'numbers',title: '序号'},
            {type:'checkbox'},
            {field: 'pointId', title: '点位id',hide:true},
            {field: 'lineId', title: '线路id',hide:true},
            {field: 'mappingId', title: '关联id',hide:true},
            {field: 'recordId', title: '记录id',hide:true},
            {field:'pointName', title:'点位名称',align : 'center' }
            ,{field:'recordInspectPerson', title:'巡检人员', align : 'center' }
            ,{field:'lineName', title:'所属线路', align : 'center' }
            ,{field:'recordInspectTime', title:'巡检时间',align : 'center', sort: true,templet:function(d){
                    return formatTime(d.recordInspectTime);
                } }
            ,{field:'recordPointStatus',align : 'center', title:'巡检结果',templet:function(d){
                    return auditState(d.recordPointStatus);
                }}
            ,{fixed: 'right', title:'操作', align : 'center',toolbar: '#barCmdOperate', width:220}
        ]]
        ,page: true
    });
    function formatTime(time){
        if(time){
            return util.toDateString(time, "yyyy-MM-dd HH:mm:ss");
        }
        return "";
    }
    // 搜索
    form.on('submit(search)',function(data){
        active['reload'].call(this);
        return false;
    });
    var active = {
        reload:function () {
            var point = $("#point_name").val();
            var line = $("#line_name").val();
            var startTime = $("#startDate").val();
            var endTime = $("#endDate").val();
            //执行重载
            table.reload('insPointRecordsTable', {
                where: {point:point,line:line,
                    startTime:startTime, endTime:endTime}
            }, 'data');
        }
    };
    // 删除
    form.on('submit(delete)',function(obj){
        var checkStatus = table.checkStatus('insPointRecordsTable');
        var	data = checkStatus.data;
        if(data.length === 0){
            layer.tips("请至少选择一个巡检记录!",this);
            return false;
        }
        var idArr = [];
        var pidArr = [];
        var midArr = [];
        for(var i in data){
            idArr[i] = data[i].recordId;
            pidArr[i] = data[i].pointId;
            midArr[i] = data[i].mappingId;
        }
        var rIds = JSON.stringify(idArr);
        var pIds = JSON.stringify(pidArr);
        var mIds = JSON.stringify(midArr);
        var params = JSON.stringify({"rIds":rIds, "pIds":pIds, "mIds":mIds});
        layer.confirm('确定要删除选择的巡检记录么',function(){
            $.ajax({
                url: baseUrl+"/insPointRecord/deleteAll",
                type: 'get',
                data: {
                    params: params
                },
                success: function (response) {
                    layer.closeAll();
                    if (response.code === 200) {
                        layer.tips("删除成功!",'#deleteRecord');
                        active['reload'].call(this);
                    }else {
                        layer.tips("删除失败!",'#deleteRecord');
                        active['reload'].call(this);
                    }
                },
                error: function () {
                    layer.closeAll();
                    layer.tips("亲,服务器内部错误,请稍后重试!",'#deleteRecord');
                }
            });
        });
        return false;
    });

    //头工具栏事件
    table.on('tool(insPointRecordsTable)', function(obj){
        //指令查看
        switch(obj.event){
            case 'recordDetail':
                showRecordsDetail(obj.data.recordId);
                break;
            case 'clockInDetail':
                showClockInDetail(obj.data);
                break;
            case 'recordDelete':
                deleteRecord(obj.data.recordId, obj.data.pointId, obj.data.mappingId);
                break;
        }
    });

    function showClockInDetail(data) {
        var params = {taskId:data.id,pointId:data.pointId,lineId:data.lineId};
        $.get(baseUrl+'/insPointRecord/getClockInDetail', params, function (response) {
            if(response != null && response.data != null){
                var data = response.data.imgs;
                var clockinTime = response.data.clockinTime;
                $("#recordClockinTime").val(formatTime(clockinTime));
                var len = data.length;
                if(len > 0){
                    var html = '<ul style="display: flex">';
                    for(var i=0; i < len; i++){
                        var imgPath = "/upload/"+data[i].path;
                        if(!imgPath){
                            imgPath = './imgs/default.jpg';//默认图片
                        }
                        var reg = new RegExp("/+","g");//g,表示全部替换。
                        imgPath = imgPath.replaceAll(reg,"/");
                        html += '<li class="ma5"><img class="headImage" src="'+imgPath+'" ></li>';
                        if(i > 0 && (i+1)%5 === 0){
                            html += '</ul><ul style="display: flex">';
                        }

                    }
                    html += '</ul>';
                    $("#xcPhotoDiv2").empty().append(html);
                }
                layer.open({
                    type: 1,
                    title:"查看打卡记录",
                    skin:'demo-class',
                    closeBtn: 1,
                    shift: 2,
                    area: ['885px', '500px'],
                    shadeClose: true,
                    btn:['确定', '取消'],
                    content: $("#clockInDetailDiv")
                });
            }
        });


    }

    table.on('tool(xjxmTable)', function(obj){
        //图片详情查看
        if(obj.event === 'xmDetail'){
            //var recordId = $($(obj.tr).find(".checkDetail")).attr("recordId");
            showSituationDetail(obj.data);
        }
    });

    function showSituationDetail(data) {
        $.get(baseUrl+'/insPointRecord/getScanPics/'+data.itemRecordId, {}, function (response) {
            if(response != null && response.data !=null){
                /*$("#problemDetail").val("");
                $("#problemDetail").val(response.msg);*/
                var len = response.data.length;
                if(len > 0){
                    var html = '<ul style="display: flex">';
                    for(var i=0; i < len; i++){
                        var imgPath = "/upload/"+response.data[i].path;
                        if(!imgPath){
                            imgPath = './imgs/default.jpg';//默认图片
                        }
                        var reg = new RegExp("/+","g");//g,表示全部替换。
                        imgPath = imgPath.replaceAll(reg,"/");
                        html += '<li class="ma5"><img class="headImage" src="'+imgPath+'" ></li>';
                        if(i > 0 && (i+1)%5 === 0){
                            html += '</ul><ul style="display: flex">';
                        }

                    }
                    html += '</ul>';
                    $("#xcPhotoDiv").empty().append(html);
                }
                $("#problemDetail").val("");
                $("#problemDetail").val(data.itemRecordDescription);
                layer.open({
                    type: 1,
                    title:"查看",
                    skin:'demo-class',
                    closeBtn: 1,
                    shift: 2,
                    area: ['885px', '500px'],
                    shadeClose: true,
                    btn:['确定', '取消'],
                    content: $("#situationDetailDiv")
                });
            }
        });


    }

    function deleteRecord(rid, pid, mid) {
        layer.confirm('确定要删除该巡检记录么?',function(){
            var param = {"rid":rid, "pid":pid, "mid":mid};
            $.get(baseUrl+"/insPointRecord/deleteRecord",param, function(data) {
                if (data.code === 200) {
                    layer.msg('删除成功');
                    active['reload'].call(this);
                }else {
                    layer.msg('删除失败，请稍后重试!');
                }
            });
        });
    }
    function showRecordsDetail(recordId) {
        // recordId 点位记录id
        table.render({
            elem: '#xjxmTable',
            url:  baseUrl+"/insPointRecord/listPointItems?recordId="+recordId,
            method: 'get',
            page: true,
            cols: [[
                {type:'numbers',title: '序号'},
                {field: 'itemsId', title: '巡检项目id',hide:true},
                {field: 'itemRecordDescription', title: '巡检结果描述',hide:true},
                {field: 'itemsName', title: '巡检项目',align:'center'},
                {field: 'itemRecordStatus', title: '巡检结果',align:'center',templet:function(d){
                        return auditState(d.itemRecordStatus);
                    }}
                ,{field: 'recordDealwith', title: '不合格处理',align:'center'},
                ,{fixed: 'right', title:'操作', align : 'center',templet:function(data){
                return '<div><a class="layui-btn layui-btn-xs checkDetail" lay-event="xmDetail">查看</a></div>';
                }}
            ]]
        });
        layer.open({
            type: 1,
            title:"查看",
            skin:'demo-class',
            closeBtn: 1,
            shift: 2,
            area: ['885px', '500px'],
            shadeClose: true,
            btn:['确定', '取消'],
            content: $("#xjxmDiv")
        });
    }
    function loadLineList(){
        $.get(baseUrl+'/insPointRecord/getLineList', {}, function (result) {
            if(result != null){
                if(result.data != null){
                    a$opt_html += "<option  value=''>全部</option>";
                    $.each(result.data, function (index, item) {
                        a$opt_html += "<option value='" + item.lineId + "'>" + item.lineName + "</option>";
                        var obj = {"key":item.lineId, "name":item.lineName};
                        if(!hasDictKey(item.lineId)){
                            dictTypeArray.push(obj);
                        }
                        $("#line_name").empty().append(a$opt_html);
                        form.render('select');
                    });

                }
            }
        });
    }
});
var a$opt_html;
var dictTypeArray = [];

function hasDictKey(key) {
    for(var i in dictTypeArray){
        if(dictTypeArray[i].key === key){
            return true;
        }
    }
    return false;
}
function reload(){
    $("#point_name").val("");
    $("#startDate").val("");
    $("#endDate").val("");
    location.reload();
}
function auditState(status){
    switch (status){
        case 0: return '合格';
        case 1: return '不合格';
        default: return "未巡检";
    }
}
